import requests
import json


def fetch_json(url):
    response = requests.get(url)
    return response.json()


def extract_image_data(json_data):
    # 提取 image_prefix
    image_prefix = json_data['image_prefix']

    # 直接获取特定的图像名称
    target_image_name = json_data['images'][4]['name']
    # 定义日期格式的正则表达式
    date_pattern = r'\d{2}\.\d{2}\.\d{4}'

    # 使用正则表达式匹配日期格式
    # 备用
    #target_images = [img for img in json_data['images'] if re.search(date_pattern, img['name'])]
    return image_prefix, target_image_name


def download_file(url, filename):
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        with open(filename, "wb") as file:
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    file.write(chunk)
        print(f"File downloaded successfully as {filename}")
    else:
        print(f"Failed to download the file. Status code: {response.status_code}")


if __name__ == "__main__":
    url = "https://openwrt.ai/json/v1/releases/targets/x86/64/generic.json"
    json_data = fetch_json(url)

    if json_data:
        # 提取 image_prefix 和特定文件信息
        image_prefix, target_image_name = extract_image_data(json_data)

        if target_image_name:
            print(f"\nImage Prefix: {image_prefix}")
            print(f"Target Image: {target_image_name}")

            # 构建下载链接
            download_url = f"https://dl.openwrt.ai/releases/targets/x86/64/{target_image_name}"
            print(f"Download Link: {download_url}")

            # 下载文件
            # download_file(download_url, target_image_name)

            download_file('https://openwrt.ai/json/v1/releases/targets/x86/64/generic.json', target_image_name)
        else:
            print("No target images were found.")